package com.xiaomaoguai.curator.common.zookeeper.server;

import com.xiaomaoguai.curator.common.model.Model;
import com.xiaomaoguai.curator.common.utils.NetAddressUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @fileName: ServerSideRigesterThread.java
 * @author: WeiHui.Zhang
 * @date: 2016-11-05  16:18
 * @version: v1.0.0
 */
public class ServerSideRegisterThread implements Runnable {

	Logger LOGGER = LoggerFactory.getLogger(ServerSideRegisterThread.class);

	private CuratorFramework curatorFramework;

	private String service;

	//当前IP
	private String ip = NetAddressUtils.getRealIp();

	//当前主机名称
	private String hostName = NetAddressUtils.getLocalHostName();

	public ServerSideRegisterThread(CuratorFramework curatorFramework, Model model) {
		this.curatorFramework = curatorFramework;
		this.service = buildServicePath(model);
	}

	private String buildServicePath(Model model) {
		String service = "";
		// 分组
		String group = model.getGroup();
		if (!group.startsWith("/")) {
			service += "/";
		}
		service += group;
		// 加上版本&版本信息
		service += "/" + StringUtils.joinWith(":", model.getService(), model.getEdition());
		// 加上提供者标志
		service += "/PROVIDER";
		return service;
	}

	@Override
	public void run() {
		LOGGER.info("begin register service : {}", service);
		//注册次数----注册7次还不成功就不再注册.
		int count = 0;
		while (count <= 7) {
			try {
				// 先保证此永久节点存在
				if (curatorFramework.checkExists().forPath(service) == null) {
					curatorFramework.create().creatingParentContainersIfNeeded().forPath(service);
				}
				// 然后正式注册---临时节点
				String key = hostName + "-[" + ip + "]";
				String value = ip;
				// 构造临时节点
				curatorFramework.create().withMode(CreateMode.EPHEMERAL).forPath(service + "/" + key, value.getBytes("UTF-8"));
				// 注册成功，就跳出循环，表示此runnable结束
				LOGGER.info("succeed to register service: " + service);
				return;
			} catch (Exception e) {
				LOGGER.error("failed to register service: " + service, e);
				count++;
				if (count > 7) {
					LOGGER.error("register service : {} failed 7 times , quit register,please check ! ", service);
					break;
				}
			}
		}
	}
}
